﻿using SixLabors.ImageSharp;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace MicroCloud.Utils
{
    /// <summary>
    /// 字节扩展方法
    /// </summary>
    public static class ByteExtensions
    {
        /// <summary>
        /// 将 <see cref="byte"/>[] 数组转换为字符串，默认编码为 <see cref="Encoding.UTF8"/>
        /// </summary>
        public static string ToStr(this byte[] bytes, Encoding encoding = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }
            return encoding.GetString(bytes);
        }

        /// <summary>
        /// 将 <see cref="byte"/>[] 数组转换为 Base64 字符串
        /// </summary>
        public static string ToBase64String(this byte[] bytes)
        {
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// 将 byte[] 编码为十六进制字符串
        /// </summary>
        /// <param name="bytes">byte[] 数组</param>
        /// <returns>十六进制字符串</returns>
        public static string ToHexString(this byte[] bytes)
        {
            return bytes.Aggregate(string.Empty, (current, t) => current + t.ToString("X2"));
        }

        /// <summary>
        /// 转换成流
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static Stream ToStream(this byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            stream.Seek(0, SeekOrigin.Begin);   //设置当前流的位置为流的开始

            return stream;
        }

        /// <summary>
        /// 转换成内存流
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static MemoryStream ToMemoryStream(this byte[] bytes)
        {
            var stream = new MemoryStream(bytes);
            stream.Seek(0, SeekOrigin.Begin);   //设置当前流的位置为流的开始

            return stream;
        }

        /// <summary>
        /// 转换为对象
        /// </summary>
        /// <param name="Bytes"></param>
        /// <returns></returns>
        public static object ToObject(byte[] Bytes)
        {
            return JsonSerializer.Deserialize<object>(Bytes);
        }

    }
}